import React from "react";
import { Form, Input, Button, message } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { connect } from 'react-redux' 
import { loginFn } from './../../api/user'

const Login = (props) => {
    const onFinish = (values) => {
        props.loginAction(values)
    }
    return (
        <div className="loginBox">
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
      >
        <Form.Item
          name="adminname"
          rules={[
            {
              required: true,
              message: '请输入管理员账户!',
            },
          ]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="管理员账户" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: '请输入正确的密码!',
            },
          ]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="密码"
          />
        </Form.Item>
        

        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">
            登 录
          </Button>
         
        </Form.Item>
      </Form>
    </div>
    )
}

export default connect(
    () => ({}),
    (dispatch) => {
        return {
            loginAction (params) {
                loginFn(params).then(res => {
                    console.log('111',res)
                    if (res.code === '10003') {
                        message.error('密码错误')
                      } else if (res.code === '10005') {
                        message.error('该管理员账户不存在')
                      } else {
                        message.success('登录成功')
                        localStorage.setItem('isLogin', true)
                        localStorage.setItem('token', res.data.token)
                        localStorage.setItem('adminname', res.data.adminname)
                        localStorage.setItem('role', res.data.role)
                        dispatch({type: 'CHANGE_ADMIN_NAME', payload: res.data.adminname})
                        dispatch({type: 'CHANGE_TOKEN', payload: res.data.token})
                        dispatch({type: 'CHANGE_ROLE', payload: res.data.role})
                        dispatch({type: 'CHANGE_LOGIN_STATE', payload: 'true'})
                        window.location.href = '/'
                      }
                })
            }
        }
    }
)(Login)